package com.song.job;


import cn.hutool.core.date.*;
import cn.hutool.core.lang.Console;
import cn.hutool.log.dialect.console.ConsoleLog;
import com.song.dao.BirthdayMapper;
import com.song.dao.IUser;
import com.song.model.Birthday;
import com.song.model.BirthdayExample;
import com.song.pojo.UserModel;

import com.song.pojo.bo.BirtydayTaskBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author 宋涛
 * @version 1.0
 * @date 2020/7/28 14:55
 */
@Component
@Slf4j
public class TimedTasks {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private BirthdayMapper birthdayMapper;
    @Autowired
    private IUser iUser;
    @Autowired
    private JavaMailSender javaMailSender;

    //    生日提醒
    @Scheduled(cron = "10 19 * * * ? ")
    public void birthdayRemind() throws InterruptedException, MessagingException {

        BirthdayExample birthdayExample = new BirthdayExample();
        BirthdayExample.Criteria criteria = birthdayExample.createCriteria();
//         通过今天查询今天的农历
        // 通过生日算出农历，在通过农历算出今年的公历
        ChineseDate todayyinDate = new ChineseDate(new Date());
        String yinStr = todayyinDate.getChineseMonth() + todayyinDate.getChineseDay();

        criteria.andBirthdayYinEqualTo(yinStr);
        List<Birthday> birthdays = birthdayMapper.selectByExample(birthdayExample);
// birthdays  今天生日的人
        DelayQueue<BirtydayTaskBO> delayQueue = new DelayQueue<>();
        for (Birthday birthday : birthdays) {
//获取用户设置的提醒时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(birthday.getAdvanceTime());
            DateTime dateTime = new DateTime();
            calendar.set(dateTime.year(), dateTime.month(), dateTime.dayOfMonth());
            long betweenDay = DateUtil.between(calendar.getTime(), new Date(), DateUnit.SECOND);
            log.info("用户：" + birthday.getName() + "已加入队列，等待通知" + "通知时间为：" + betweenDay + " s");
            BirtydayTaskBO Order1 = new BirtydayTaskBO(birthday, betweenDay, TimeUnit.SECONDS);
            delayQueue.put(Order1);

        }

        System.out.println("通知延迟队列开始时间:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        while (delayQueue.size() != 0) {
            /**
             * 取队列头部元素是否过期
             */
            BirtydayTaskBO task = delayQueue.poll();
            if (task != null) {
//                开始通知
                UserModel userbyId = iUser.getUserbyId(task.getBirthday().getUId());
                userbyId.getEmail();
                SendEmail(task.getBirthday(), userbyId);
                log.info("通知:{}已通知, 通知时间:{}", task.getBirthday(), LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            Thread.sleep(500);

        }
    }

    private void SendEmail(Birthday birthday, UserModel userbyId) throws MessagingException {

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setSubject(birthday.getName() + "生日快乐");
        messageHelper.setFrom("508436045@qq.com");
        messageHelper.setTo(userbyId.getEmail());
        messageHelper.setText("<h1>" + birthday.getName() + "生日快乐" + "</h1><br/><p>今天是你的生日，你要开开心心的过好每一天哟</p>", true);
        javaMailSender.send(messageHelper.getMimeMessage());

    }


}
